<template>
  <div>
    <!-- 取消父子关联 check-strictly -->
    <!-- node-key 如果需要通过 key 来获取或设置，则必须设置node-key。 -->
    <el-tree
      ref="tree"
      node-key="id"
      :data="permissionList"
      show-checkbox
      default-expand-all
      check-strictly
      :props="{label: 'name'}"
    />

    <el-row class="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button size="small" @click="cancelButton">取 消</el-button>
        <el-button size="small" type="primary" @click="setRolesBtn">确 定</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { transListToTree } from '@/utils'
import { getRoleDetail, assignRoleById } from '@/api/setting'
export default {
  name: 'AssignPermission',
  props: {
    roleId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      permissionList: []
    }
  },
  created() {
    this.getPermissionList()
    this.getRoleDetail()
  },
  methods: {
    // 获取权限点
    async getPermissionList() {
      const res = await getPermissionList()
      // console.log(res)
      this.permissionList = transListToTree(res.data, '0')
    },
    // 获取角色详情(权限)
    async getRoleDetail() {
      const res = await getRoleDetail(this.roleId)
      console.log(res)
      this.$refs.tree.setCheckedKeys(res.data.permIds)
    },

    // 取消按钮
    cancelButton() {
      this.$emit('close')
    },

    // 设置权限按钮
    async setRolesBtn() {
      const permIds	 = this.$refs.tree.getCheckedKeys()
      const res = await assignRoleById({ id: this.roleId, permIds })
      this.$message.success(res.message)
      this.$emit('close')
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  margin-top: 30px;
}
</style>
